//
//  Group.swift
//  GhostWorld
//
//  Created by Kam on 2018/4/3.
//  Copyright © 2018 LKGood. All rights reserved.
//

import Foundation
import CoreData

private let entityName = CoreDataEntityName.group.rawValue
private let context = CoreDataHelper.getContext()

struct SimpleGroup {
  var identifier: Int
  var name: String
}

extension Group {
  enum DefaultGroupIdentifer: Int {
    case guiYingRenJian = 1
  }
  
  var children: [Group]? {
    get {
      let request = NSFetchRequest<Group>()
      request.entity = NSEntityDescription.entity(forEntityName: entityName, in: context)
      request.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)]
      request.predicate = NSPredicate(format: "parentID = %@", "\(id)")
      do {
        let cdGroups = try context.fetch(request)
        return cdGroups
      } catch let error {
        loggingPrint(error)
        return nil
      }
    }
  }
  
  var parent: Group? {
    get {
      let id = Int(parentID)
      return EntityManager.fetch(Group.self, fetchType: .id(id))?.first
    }
  }
  
  var cover: RemoteImage {
    get {
      return RemoteImage(origianlPath: coverOriginal, mediumPath: nil, thumbPath: coverThumb)
    }
  }
  
  public override var description: String {
    var childrenString = ""
    if let children = self.children {
      childrenString = children.map {
        "\($0.id)"
      }.joined(separator: ",")
    }
    return "[Group] id: \(id), name: \(name ?? "--"), parent: \(parent != nil ? "\(parent!.id)" : "nil"), children: \(childrenString.count > 0 ? childrenString : "nil")"
  }
}
